<template>
  <view class="container">
    <view class="subject">
      <text>学科：</text>
      <radio-group @change="subject_change">
        <label v-for="(item, index) in subject_list" :key="index">
          <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
          {{ item.name }}
        </label>
      </radio-group>
    </view>
    <view class="has_applied">
      <text>是否申请过</text>
      <radio-group @change="revisable_apply_change">
        <label v-for="(item, index) in revisable_apply_select_list" :key="index">
          <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
          {{ item.name }}
        </label>
      </radio-group>
    </view>
    <view class="revisable_paper_list">
      <uni-card v-for="(item, index) in paper_list" :key="index" :title="item.title" :extra="has_applied(item.id)"
        class="guide-content" @click="onclickCard(item.id, index)">
        <view class="card_content">
          <text class="expiration">截止日期：{{ item.expiration }}</text>
          <text class="grade">年级：{{ item.grade }}</text>
        </view>
      </uni-card>
    </view>
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog cancelText="取消" confirmText="申请" message="您确定申请该试卷的上传权限吗？" type="success" title="申请权限"
        content="您确定申请该试卷的上传权限吗？" :duration="2000" :before-close="true" @close="onClosePopup"
        @confirm="onConfirmPopup"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { SelectTypeItem, ExaminationPaperItem, SubjectItem, OnlyIdItem } from '@/types/home'
import {
  getAppliedPaperAPI,
  getRevisablePaperAPI,
  postPermitAPI,
  getAppliedAndApprovedPaperAPI,
} from '@/services/home'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
const state = reactive({
  select_paper_id: 0,
  subject_id: 1,
  revisable_apply_paper_type: 0,
  page: 1,
  size: 10,
  total: 1,
})
// 弹窗
const popup = ref()
// 弹窗关闭处理事件
const onClosePopup = () => {
  popup.value.close()
}
// 弹窗确定事件, 申请录入试卷的权限，并刷新当前的试卷列表
const onConfirmPopup = () => {
  console.log('点击了确定', state.select_paper_id)
  postPerimit()
  popup.value.close()
  getRevisablePaperData()
}
// 可录入试卷的是否申请过选择框选项
const revisable_apply_select_list = ref<SelectTypeItem[]>([
  { name: '全部', value: '0', checked: true },
  { name: '已申请', value: '1', checked: false },
  { name: '未申请', value: '2', checked: false },
])
// 可选择的学科选项
const subject_list = ref<SubjectItem[]>([
  { name: '信息', value: '1', checked: true },
  { name: '通用', value: '2', checked: false },
  { name: '职高', value: '3', checked: false },
])
// 发送申请试卷允许录入权限
const postPerimit = async () => {
  const data = {
    paper: state.select_paper_id,
  }
  const res = await postPermitAPI(data)
  console.log('提交申请解析权限', res)
  if (res.code === 200) {
    uni.showToast({ icon: 'success', title: '提交成功' })
  } else if (res.code === 1022) {
    uni.showToast({ icon: 'error', title: '你已经申请过，联系管理员审批' })
  } else {
    uni.showToast({ icon: 'error', title: '提交错误' })
  }
}
// 显示到页面的可录入的试卷，且未过期
const paper_list = ref<ExaminationPaperItem[]>([])
const getRevisablePaperData = async () => {
  const data = {
    applied_type: state.revisable_apply_paper_type,
    subject_id: state.subject_id,
    page: state.page,
    size: state.size,
  }
  const res = await getRevisablePaperAPI(data)
  console.log('可上传且未过期的试卷', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    paper_list.value = res.results
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 添加可录入试卷列表，且未过期，用于上拉触底新增数据
const addRevisablePaperData = async () => {
  const data = {
    applied_type: state.revisable_apply_paper_type,
    subject_id: state.subject_id,
    page: state.page + 1,
    size: state.size,
  }
  const res = await getRevisablePaperAPI(data)
  console.log('可上传且未过期的试卷', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    paper_list.value.push(...res.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
// 用户已经申请过的试卷列表id, 用于显示该试卷是否申请过。
const has_applied_paper_id_list = ref<PaperId[]>([])
const getAppliedPaperData = async () => {
  const res = await getAppliedPaperAPI()
  console.log('获取当前用户已经申请过的未过期的试卷', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    has_applied_paper_id_list.value = res.results
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 用户已经申请过的试卷并已经被批准的试卷列表id,用于显示该试卷是否已经被批准
const has_applied_and_approved_paper_id_list = ref<PaperId[]>([])
const getAppliedAndApprovedPaperData = async () => {
  const res = await getAppliedAndApprovedPaperAPI()
  console.log('获取当前用户已经申请过的且被批准的试卷', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    has_applied_and_approved_paper_id_list.value = res.results
    console.log('获取批准列表成功：', has_applied_and_approved_paper_id_list.value)
    // uni.showToast({ icon: 'success', title: '获取批准列表成功' })
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 选择了不同状态
const revisable_apply_change = (e: any) => {
  console.log('申请状态改变了', e.target.value)
  state.revisable_apply_paper_type = e.target.value
  state.page = 1
  getRevisablePaperData()
}
// 学科改变了,重新获取该学科的知识点
const subject_change = (e: any) => {
  console.log('学科改变：', e.target.value)
  state.page = 1
  state.subject_id = e.target.value
  getRevisablePaperData()
}
// 点击卡片事件，如果是用户申请过的，则进入三级页面具体试题；否则进入申请页面
const onclickCard = (paper_id: number, index: number) => {
  console.log('点击卡片页面', paper_id)
  state.select_paper_id = paper_id
  if (!containsObjectById(has_applied_paper_id_list.value, paper_id)) {
    console.log('未申请，现在去申请', paper_id)
    popup.value.open()
  } else if (!containsObjectById(has_applied_and_approved_paper_id_list.value, paper_id)) {
    console.log('管理员未审批', paper_id)
    uni.showToast({ icon: 'error', title: '管理员未审批' })
  } else {
    uni.navigateTo({
      url: `step_three_question_list?paper_id=${paper_id}&subject_id=${state.subject_id}&paper_title=${paper_list.value[index].title}`,
    })
  }
}
type PaperId = {
  paper: number
}
const containsObjectById = (array: Array<PaperId>, obj: number) => {
  return array.some((element) => element.paper === obj)
}
// 返回该id的试卷是否申请过
const has_applied = (paper_id: number) => {
  if (containsObjectById(has_applied_and_approved_paper_id_list.value, paper_id)) {
    return '已批准'
  } else {
    // console.log('比较是否含有申请：', has_applied_paper_id_list.value)
    if (containsObjectById(has_applied_paper_id_list.value, paper_id)) {
      return '未批准'
    } else {
      return '未申请'
    }
  }
}
// 页面加载
onLoad(async () => {
  await Promise.all([
    getRevisablePaperData(),
    getAppliedPaperData(),
    getAppliedAndApprovedPaperData(),
  ])
})
// 自定义下拉刷新被触发
onPullDownRefresh(async () => {
  paper_list.value = []
  state.page = 1
  await Promise.all([
    getRevisablePaperData(),
    getAppliedPaperData(),
    getAppliedAndApprovedPaperData(),
  ])
  // 停止页面加载动画
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 自定义触底加载更多数据
onReachBottom(async () => {
  if (paper_list.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    await Promise.all([addRevisablePaperData()])
  }
})
</script>
<style lang="scss" scoped>
.card_content {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.container {
  font-size: 28rpx;
}

.subject,
.has_applied {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: left;
}
</style>
